﻿using Abp.ObjectMapping;
using AVIS.OutBound.BookOrders;
using AVIS.OutBound.Orders.Dto;

namespace AVIS.OutBound.Orders
{
    /// <summary>
    /// 在线预定的应用服务类
    /// </summary>
    public class OrderAppService : OutBoundAppServiceBase, IOrderAppService
    {
        #region 构造函数
        private readonly IOrderManager _orderManager;
        private readonly IBookOrderManager _bookOrderManager;
        private readonly IObjectMapper _objectMapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        public OrderAppService(
                IOrderManager orderManager,
                IBookOrderManager bookOrderManager,
                IObjectMapper objectMapper)
        {
            _orderManager = orderManager;
            _bookOrderManager = bookOrderManager;
            _objectMapper = objectMapper;
        }
        #endregion

        /// <summary>
        /// 提交订单（预订单方式）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public SubmitOrderOutput Submit(SubmitOrderInput input)
        {
            // 1. 保存预订单的信息（合并当前步骤提交的信息）
            var bookOrder = _objectMapper.Map<BookOrder>(input);
            _bookOrderManager.SaveBookOrderCache(bookOrder);

            // 2. 获取完整的预定单信息并转化为订单信息
            var cacheBookOrder = _bookOrderManager.GetBookOrder(input.OrderId);
            var order = _objectMapper.Map<Order>(cacheBookOrder);

            // 3. 提交订单到Wizard接口并保持订单信息到数据库
            _orderManager.SubmitOrder(order);

            // 4. 再次保存预订单的信息（更新订单提交状态和订单号）
            cacheBookOrder.IsSubmit = true; // 设置订单已经提交
            cacheBookOrder.OrderNo = order.OrderNo;
            _bookOrderManager.SaveBookOrderCache(cacheBookOrder);

            return new SubmitOrderOutput { OrderNo = order.OrderNo, Surname = order.Surname };
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public CancelOrderOutput Cancel(CancelOrderInput input)
        {
            var request = _objectMapper.Map<AgentCancelOrderRequest>(input);
            var result = _orderManager.CancelOrder(request);
            return new CancelOrderOutput { Result = result };
        }


        /// <summary>
        /// 查询订单（按订单号和用户姓查询）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public OrderOutput Detail(QueryOrderInput input)
        {
            var order = _orderManager.QueryOrder(input.OrderNo.Trim(), input.Surname.Trim());
            var output = _objectMapper.Map<OrderOutput>(order);

            // 设置取还车的营业时间
            output.PickUpStore.ShopOpenTime = order.PickUpStore.DayOpenTime(order.PickupDateTime);
            output.ReturnStore.ShopOpenTime = order.ReturnStore.DayOpenTime(order.ReturnDateTime);

            return output;
        }
    }
}
